class Solution {
public:
   
    vector<int> dx={0,0,1,-1};
    vector<int> dy={1,-1,0,0};
    std::array<std::array<int, 1000>, 1000> v;
    queue<pair<int,int>> q;
    int rotApple(vector<vector<int> >& grid) {
        for(auto e:v)
        {
            e.fill(-1e5);
        }
        int n=grid.size();
        int m=grid[0].size();
         for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(grid[i][j]==2)
                {
                    
                    q.push({i,j});
                   
                }
            }   
        }
        
        while(q.size())
        {
            auto p=q.front();
            q.pop();
            for(int k=0;k<4;k++)
            {
                int x=p.first+dx[k];int y=p.second+dy[k];
                if(x<0||x>=grid.size()||y<0||y>=grid[0].size()||grid[x][y]==0||grid[x][y]==2) continue;//注意这个地方条件判断的先后顺序。不然会越界访问
                v[x][y]=v[p.first][p.second]+1;
                q.push({x,y});
                grid[x][y]=2;//别忘了改
            }
        }
        int ret=0;
        for(int i=0;i<grid.size();i++)
        {
            for(int j=0;j<grid[i].size();j++)
            {
                if(grid[i][j]==1)
                {
                    return -1;
                }
                ret=max(ret,v[i][j]);
            }   
        }
        return ret;
    }
};